package com.eagle.ant.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.eagle.ant.MainActivity;
import com.eagle.ant.activity.WeatherActivity;
import com.eagle.ant.view.ChooseViewTask;
import com.eagle.ant.R;
import com.eagle.ant.adapter.SelectAdapter;
import com.eagle.ant.db.City;
import com.eagle.ant.db.County;
import com.eagle.ant.db.Province;
import com.eagle.ant.util.HttpUtil;
import com.eagle.ant.util.Utility;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Name:
 * User: eagle
 * Date: 2020/1/6
 * Desc: 选择地区
 */
public class ChooseAreaFragment extends Fragment implements ChooseViewTask {
    private static final String TAG = "ChooseAreaFragment";
    private static final int LEVEL_PROVINCE = 0;
    private static final int LEVEL_CITY = 1;
    private static final int LEVEL_COUNTY = 2;

    @BindView(R.id.id_title_textView)
    TextView mTitleTextView;
    @BindView(R.id.id_back_button)
    Button mBackButton;
    @BindView(R.id.id_recyclerView)
    RecyclerView mRecyclerView;

    private ProgressDialog mProgressDialog;

    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    private List<String> mDataList;
    private SelectAdapter mListAdapter;

    /**
     * 选中的省份
     */
    private Province selectProvince;

    /**
     * 选中的城市
     */
    private City selectCity;

    /**
     * 当前选中的级别
     */
    private int currentLevel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View itemView = inflater.inflate(R.layout.fragment_choose_area, container, false);
        ButterKnife.bind(this, itemView);
        return itemView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mDataList = new ArrayList<>();
        mListAdapter = new SelectAdapter(getActivity());
        mListAdapter.setViewTask(this);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mListAdapter);
        queryProvinces();
    }

    @Override
    public void selectAreaTask(int position) {
        if (currentLevel == LEVEL_PROVINCE) {
            selectProvince = provinceList.get(position);
            queryCities();
        } else if (currentLevel == LEVEL_CITY) {
            selectCity = cityList.get(position);
            queryCounties();
        } else if (currentLevel == LEVEL_COUNTY) {
            String weatherId = countyList.get(position).getWeatherId();
            if (getActivity() instanceof MainActivity) {
                Intent intent = new Intent(getActivity(), WeatherActivity.class);
                intent.putExtra("weather_id", weatherId);
                startActivity(intent);
                getActivity().finish();
            } else if (getActivity() instanceof WeatherActivity){
                WeatherActivity activity = (WeatherActivity) getActivity();
                activity.mDrawerLayout.closeDrawers();
                activity.mRefreshLayout.setRefreshing(true);
                activity.requestWeather(weatherId);
            }
        }
    }

    @OnClick({
            R.id.id_back_button
    })
    public void onClick() {
        if (currentLevel == LEVEL_COUNTY) {
            queryCities();
        } else if (currentLevel == LEVEL_CITY) {
            queryProvinces();
        }
    }

    /**
     * 查询全国所有的省份，优先从数据库查询，如果没有查询再去服务器上查询
     */
    private void queryProvinces() {
        mTitleTextView.setText("中国");
        mBackButton.setVisibility(View.GONE);
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0) {
            Log.e(TAG, "省份数据：" + provinceList.get(0).getProvinceName());
            mDataList.clear();
            for (Province province: provinceList) {
                mDataList.add(province.getProvinceName());
            }
            mListAdapter.setDataList(mDataList);
            mListAdapter.notifyDataSetChanged();
            currentLevel = LEVEL_PROVINCE;
        } else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address, "province");
        }
    }

    /**
     * 查询选中省内所有的市，优先从数据库查询，如果没有再去服务器查询
     */
    private void queryCities() {
        mTitleTextView.setText(selectProvince.getProvinceName());
        mBackButton.setVisibility(View.VISIBLE);
        cityList = DataSupport.where("provinceId = ?", String.valueOf(selectProvince.getId())).find(City.class);
        if (cityList.size() > 0) {
            mDataList.clear();
            for (City city: cityList) {
                mDataList.add(city.getCityName());
            }
            mListAdapter.setDataList(mDataList);
            mListAdapter.notifyDataSetChanged();
            currentLevel = LEVEL_CITY;
        } else {
            int provinceCode = selectProvince.getProvinceCode();
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address, "city");
        }
    }

    /**
     * 查询市内所有的县，优先从数据库查询，如果没有再去服务器查询
     */
    private void queryCounties() {
        mTitleTextView.setText(selectCity.getCityName());
        mBackButton.setVisibility(View.VISIBLE);
        countyList = DataSupport.where("cityId = ?", String.valueOf(selectCity.getId())).find(County.class);
        if (countyList.size() > 0) {
            mDataList.clear();
            for (County county: countyList) {
                mDataList.add(county.getCountyName());
            }
            mListAdapter.setDataList(mDataList);
            mListAdapter.notifyDataSetChanged();
            currentLevel = LEVEL_COUNTY;
        } else {
            int provinceCode = selectProvince.getProvinceCode();
            int cityCode = selectCity.getCityCode();
            String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    /**
     * 根据地址和类型从服务器上查询省市县数据
     */
    private void queryFromServer(String address, String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(() -> {
                    closeProgressDialog();
                    Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                Log.e(TAG, data);
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(data);
                } else if ("city".equals(type)) {
                    result = Utility.handleCityResponse(data, selectProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountyResponse(data, selectCity.getId());
                }
                if (result) {
                    getActivity().runOnUiThread(() -> {
                        closeProgressDialog();
                        switch (type) {
                            case "province":
                                queryProvinces();
                                break;
                            case "city":
                                queryCities();
                                break;
                            case "county":
                                queryCounties();
                                break;
                        }
                    });
                }
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.setCanceledOnTouchOutside(false);
        }
        mProgressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
}
